package com.wugui.datax.admin.tool.datax.writer;

import com.google.common.collect.Maps;
import com.wugui.datax.admin.tool.pojo.DataxDorisPojo;
import com.wugui.datax.admin.tool.pojo.DataxHivePojo;

import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Boomlee
 * @description TODO
 * @date 2024/11/13 11:27
 */

public class Doriswriter extends BaseWriterPlugin implements DataxWriterInterface {
    @Override
    public String getName() {
        return "doriswriter";
    }


    @Override
    public Map<String, Object> sample() {
        return null;
    }

    @Override
    public Map<String, Object> buildDoris(DataxDorisPojo plugin) {
        Map<String, Object> writerObj = Maps.newLinkedHashMap();
        writerObj.put("name", getName());
        Map<String, Object> parameterObj = Maps.newLinkedHashMap();
        parameterObj.put("flushInterval", plugin.getFlushInterval());
        parameterObj.put("username", plugin.getJdbcDatasource().getJdbcUsername());
        parameterObj.put("password", plugin.getJdbcDatasource().getJdbcPassword());
        parameterObj.put("column", plugin.getColumn());
        parameterObj.put("loadProps", plugin.getLoadProps());
        Map<String, Object> connectionObj = Maps.newLinkedHashMap();
        String jdbcUrl = plugin.getJdbcDatasource().getJdbcUrl();
        String dbName = "";
        if (plugin.getJdbcDatasource().getDatabaseName() == null) {
            dbName = jdbcUrl.substring(jdbcUrl.lastIndexOf("/") + 1);
        } else {
            dbName = plugin.getJdbcDatasource().getDatabaseName();
        }
        String loadUrls = plugin.getJdbcDatasource().getLoadUrls();
        //判断是否为逗号分割的字符串
        List<String> urlList = new ArrayList<>();
        if (loadUrls != null && !loadUrls.isEmpty()) {
            String[] urls = loadUrls.split(",");
            for (String url : urls) {
                urlList.add(url.trim());  // 将每个 URL 加入集合，trim() 去除两端的空格
            }
        }
        parameterObj.put("loadUrl", urlList);
        connectionObj.put("selectedDatabase", dbName);
        connectionObj.put("jdbcUrl", plugin.getJdbcDatasource().getJdbcUrl());
        connectionObj.put("table", plugin.getTables());
        ArrayList<Map<String, Object>> conn = new ArrayList<>();
        conn.add(connectionObj);
        parameterObj.put("connection", conn);
        writerObj.put("parameter", parameterObj);
        return writerObj;
    }

}
